package scut.facerecognition.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import scut.facerecognition.entity.dto.PageResult;
import scut.facerecognition.entity.dto.PostDTO;
import scut.facerecognition.entity.pojo.User;
import scut.facerecognition.entity.pojo.Post;
import scut.facerecognition.entity.pojo.PostLike;
import scut.facerecognition.mapper.UserMapper;
import scut.facerecognition.mapper.PostLikeMapper;
import scut.facerecognition.mapper.PostMapper;
import scut.facerecognition.service.PostService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 帖子服务实现类
 */
@Service
public class PostServiceImpl implements PostService {
    
    @Autowired
    private PostMapper postMapper;
    
    @Autowired
    private PostLikeMapper postLikeMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 日期时间格式化器
     */
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public PageResult<PostDTO> getPostList(int page, int size, int sort, Long userId) {
        // 创建分页对象
        Page<Post> pageParam = new Page<>(page, size);
        IPage<Post> postPage;
        
        // 按不同的排序方式查询
        if (sort == 1) {  // 最热
            postPage = postMapper.selectPostsByLikes(pageParam);
        } else {  // 最新
            postPage = postMapper.selectPostsByTime(pageParam);
        }
        
        // 转换为DTO列表
        List<PostDTO> postDTOList = new ArrayList<>();
        for (Post post : postPage.getRecords()) {
            PostDTO dto = convertToDTO(post, userId);
            postDTOList.add(dto);
        }
        
        // 返回分页结果
        return new PageResult<>(
                postDTOList,
                postPage.getTotal(),
                postPage.getCurrent(),
                postPage.getSize()
        );
    }
    
    @Override
    public PostDTO getPostDetail(Long id, Long userId) {
        // 获取帖子详情
        Post post = postMapper.selectById(id);
        if (post == null || post.getStatus() != 1) {
            return null;
        }
        
        // 增加浏览量
        postMapper.incrementViewCount(id);
        post.setViewCount(post.getViewCount() + 1);
        
        // 转换为DTO并返回
        return convertToDTO(post, userId);
    }
    
    @Override
    @Transactional
    public Long createPost(Post post) {
        // 设置初始值
        post.setStatus(1);
        post.setLikeCount(0);
        post.setViewCount(0);
        post.setCommentCount(0);
        LocalDateTime now = LocalDateTime.now();
        post.setAddTime(now);
        post.setUpdateTime(now);
        
        // 保存到数据库
        postMapper.insert(post);
        
        return post.getId();
    }
    
    @Override
    @Transactional
    public boolean updatePost(Post post) {
        // 获取原帖子
        Post oldPost = postMapper.selectById(post.getId());
        if (oldPost == null || oldPost.getStatus() != 1) {
            return false;
        }
        
        // 只更新标题和内容
        Post updatePost = new Post();
        updatePost.setId(post.getId());
        updatePost.setTitle(post.getTitle());
        updatePost.setContent(post.getContent());
        updatePost.setUpdateTime(LocalDateTime.now());
        
        return postMapper.updateById(updatePost) > 0;
    }
    
    @Override
    @Transactional
    public boolean deletePost(Long id, Long userId) {
        // 获取原帖子
        Post post = postMapper.selectById(id);
        if (post == null || post.getStatus() != 1) {
            return false;
        }
        
        // 验证权限
        if (!post.getUserId().equals(userId)) {
            return false;
        }
        
        // 逻辑删除
        Post updatePost = new Post();
        updatePost.setId(id);
        updatePost.setStatus(2);  // 已删除
        
        return postMapper.updateById(updatePost) > 0;
    }
    
    @Override
    @Transactional
    public Object[] togglePostLike(Long postId, Long userId) {
        // 查询是否已点赞
        Long likeId = postLikeMapper.isPostLikedByUser(postId, userId);
        
        boolean liked;
        if (likeId == null) {
            // 添加点赞
            PostLike postLike = new PostLike();
            postLike.setPostId(postId);
            postLike.setUserId(userId);
            postLike.setAddTime(LocalDateTime.now());
            postLikeMapper.insert(postLike);
            
            // 更新帖子点赞数
            postMapper.incrementLikeCount(postId);
            liked = true;
        } else {
            // 取消点赞
            postLikeMapper.deleteById(likeId);
            
            // 更新帖子点赞数
            postMapper.decrementLikeCount(postId);
            liked = false;
        }
        
        // 获取更新后的点赞数
        Post post = postMapper.selectById(postId);
        int likeCount = post != null ? post.getLikeCount() : 0;
        
        return new Object[]{liked, likeCount};
    }
    
    /**
     * 将帖子实体转换为DTO
     * @param post 帖子实体
     * @param currentUserId 当前用户ID
     * @return 帖子DTO
     */
    private PostDTO convertToDTO(Post post, Long currentUserId) {
        PostDTO dto = new PostDTO();
        dto.setId(post.getId());
        dto.setTitle(post.getTitle());
        dto.setContent(post.getContent());
        dto.setLikeCount(post.getLikeCount());
        dto.setViewCount(post.getViewCount());
        dto.setCommentCount(post.getCommentCount());
        dto.setAddTime(post.getAddTime().format(DATE_FORMATTER));
        dto.setUpdateTime(post.getUpdateTime().format(DATE_FORMATTER));
        dto.setUserId(post.getUserId());
        
        // 获取用户信息
        User user = userMapper.selectById(post.getUserId());
        if (user != null) {
            dto.setUserNickname(user.getNickname());
            dto.setUserPhoto(user.getPhoto());
        }
        
        // 判断当前用户是否点赞
        if (currentUserId != null) {
            Long likeId = postLikeMapper.isPostLikedByUser(post.getId(), currentUserId);
            dto.setIsLiked(likeId != null);
        } else {
            dto.setIsLiked(false);
        }
        
        return dto;
    }
}
